<?php
/**
* phpCan - http://idc.anavallasuiza.com/
*
* phpCan is released under the GNU Affero GPL version 3
*
* More information at license.txt
*/

namespace i18n;

defined('ANS') or die();

class Datetime extends \DateTime {
	private $Debug;

	public function __construct ($time = 'now', $timezone = NULL) {
		global $Debug;

		$this->Debug = $Debug;
		
		if (!$time) {
			return parent::__construct();
		}

		if (preg_match('/^[0-9]+$/', $time)) {
			parent::__construct();

			$this->setTimeStamp($time);

			return $this;
		}
	
		if (!$timezone) {
			return parent::__construct($time);
		}

		return parent::__construct($time, $timezone);
	}

	public function __format ($format = 'default') {
		global $Config;

		if (is_string($format)) {
			if ($Config['i18n']['time_formats'][$format]) {
				$time_formats = $Config['i18n']['time_formats'][$format];
			} else {
				$time_formats = array(array($format));
			}
		} else {
			$time_formats = isMultidimensionalArray($format) ? $format : array($format);
		}

		krsort($time_formats);

		$Now = new \DateTime('now');

		$diff = $this->diff($Now);

		$diff_seconds = ($diff->days * 86400) + ($diff->h * 3600) + ($diff->i * 60) + $diff->s;

		if ($diff->invert) {
			$diff_seconds = -$diff_seconds;
		}

		$array_time_formats_seconds = array_keys($time_formats);

		$k = 0;

		foreach ($time_formats as $time_formats_seconds => $time_formats_value) {
			list($format, $absolute) = $time_formats_value;

			if ($diff_seconds >= $time_formats_seconds || !array_key_exists(++$k, $array_time_formats_seconds)) {
				preg_match_all('(\$([a-zA-z]))', $format, $matches, PREG_SET_ORDER);

				if (!$matches) {
					return $format;
				}
				
				$format_chars = array();

				foreach ($matches as $match) {
					$format_chars[] = $match[1];
				}

				if ($absolute) {
					$format_chars = $this->format(implode(',', $format_chars));
				} else {
					$format_chars = $diff->format('%'.implode(',%', $format_chars));
				}

				$format_chars = explode(',', $format_chars);

				$replaces = array();

				foreach ($format_chars as $k => $value) {
					$char = $matches[$k][0];

					if (array_key_exists($char.'_'.$value, $Config['i18n']['time_translations'])) {
						$value = $Config['i18n']['time_translations'][$char.'_'.$value];
					}

					$replaces[$char] = $value;
				}

				return strtr($format, $replaces);
			}
		}
	}
}